<?php

require "../utility.php";

function genOrder(mysqli $conn, string $user_id, string $addr, array $books): bool {
    $conn->begin_transaction(MYSQLI_TRANS_START_READ_WRITE);

    try {
        // 先生成 Order
        $time = time();
        $rand = rand();
        $order_id = md5("$user_id$time$rand");
        $order_insert_str = "INSERT INTO Orders (ID, userID, address) VALUES(?, ?, ?);";
        $order_insert_stmt = $conn->prepare($order_insert_str);
        $order_insert_stmt->bind_param("sis", $order_id, $user_id, $addr);
        if (!$order_insert_stmt->execute()) {
            $conn->rollback();
            return false;
        }
        // 再根据 books 生成 OrderBooks
        $book_insert_str = "INSERT INTO OrderBooks (orderID, bookID, cnt) VALUES(?, ?, ?);";
        $book_insert_stmt = $conn->prepare($book_insert_str);
        foreach ($books as $book) {
            $book_id = $book["bookID"];
            $cnt     = $book["cnt"];
            $book_insert_stmt->bind_param("sii", $order_id, $book_id, $cnt);
            if (!$book_insert_stmt->execute()) {
                $conn->rollback();
                return false;
            }
        }
        return $conn->commit();
    } catch (mysqli_sql_exception) {
        $conn->rollback();
        return false;
    }
}

$conn = connect_mysql();
$user_id = getUserIdBySessionId($conn);

$json = getJsonDataFromRawInput();

http_response_code(403);

if ($user_id !== null &&
    check_keys($json, "address", "books")) {
    
    $addr  = $json["address"];
    $books = $json["books"];

    if ($addr !== "" && check_keys($books[0], "bookID", "cnt")) {
        if (genOrder($conn, $user_id, $addr, $books)) {
            http_response_code(200);
        }
    }
}

?>